﻿using ACC.Business;
using ACC.Business.Process;
using ACC.Business.Stn;
using ACC.Business.Utils;
using ACC.Data;
using ACC.Data.Comm;
using ACC.Data.Line;
using ACC.Device;
using ACC.LineDevice.KukaPack;
using ACC.Interface.Extensions;
using System;

namespace Script
{
    /// <summary>
    /// 上盖上线/安装防水透气阀， 人工
    /// OP L1P10040, STATION  L1P100041
    /// </summary>
    public class L1P10040 : StnProcessKukaClientWithPLC
    {
        public L1P10040(StnRunningData data)
            : base(data)
        {
            IsACCReport = true;
            PlcName = "PLC170";
        }

        protected override ACCDevice CreateDevice()
        {
            ACCDevice dev = base.CreateDevice();
            if (kukaSiemensDev != null)
            {
                kukaSiemensDev.DB190 = 800;
                kukaSiemensDev.DB190_Offset = 6000;
                kukaSiemensDev.DB192 = 80;
                kukaSiemensDev.DB192_PLC_Offset = 6066; // TO-DO: 66 ?
                kukaSiemensDev.DB193 = 800;
                kukaSiemensDev.DB193_PLC_Offset = 6034;
                kukaSiemensDev.DB193_ACC_Offset = 6068;
                kukaSiemensDev.DB194 = 800;
                kukaSiemensDev.DB194_PLC_Offset = 6034;
                kukaSiemensDev.DB194_PLC_Data_Offset = 6076;
            }

            return dev;
        }

        public override ACCCode ReadLoadParam(ACCDevice dev, out ACCDevice.LoadParam param)
        {
            ACCCode rs = base.ReadLoadParam(dev, out param);
            if(rs == ACCCode.ACCOK)
            {
                param.UnitSN = CreateVirtualBarcode();
            }

            return rs;
        }

        public override ACCCode SendLoadResult(ACCDevice dev, ACCDevice.LoadResult result)
        {
            if (result.ErrorCode == ACCCode.ACCOK && kukaSiemensDev != null)
            {
                // TO-DO: 将上箱体条码写入PLC 
                result.ErrorCode = SendBarcodeToPlc(new string[] { _data.LastLoadUnit.UnitSN }, kukaSiemensDev.DB190_Offset + 2, 30);

                // TO-DO: 写入产品型号和数量
            }
            return base.SendLoadResult(dev, result);
        }

        //public override ACCCode ReadUnloadParam(ACCDevice dev, out ACCDevice.UnloadParam param)
        //{
        //    ACCCode rs = base.ReadUnloadParam(dev, out param);
        //    if (rs == ACCCode.ACCOK)
        //    {
        //        param.UnitSN = _data.LastLoadUnit.UnitSN;
        //    }

        //    return rs;
        //}

        /// <summary>
        /// 生成上箱体码
        /// </summary>
        /// <returns></returns>
        public string CreateVirtualBarcode()
        {
            logger.Debug("Begin Create SXT Barcode");
            string barcode = PartTypeTagProcess.GetPartTypeTagValue(_data.PartNo.BomCfg, "SXTSN", logger);
            barcode = barcode.Replace("-", "");
            return barcode;
        }

    }
}